/*
 * Copyright (c) 2006 - 2022, webrx.cn All rights reserved.
 *
 */
package cn.demo;

import java.util.Arrays;
import java.util.Random;
import java.util.function.IntConsumer;
import java.util.stream.Collectors;
import java.util.stream.DoubleStream;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * <p>Project: app2022 - IntStreamDemo
 * <p>Powered by webrx On 2022-01-26 10:08:40
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
public class IntStreamDemo {
    public static void main(String[] args) {
        var rand = new Random();
        var is = IntStream.generate(() -> rand.nextInt(1, 101)).limit(10).skip(0);
        //is.forEach(System.out::println);

        //升序输出
        //is.sorted().forEach(System.out::println);

        //降序输出Stream<Integer> 有sorted()
        //is.boxed().sorted((a, b) -> b - a).forEach(System.out::println);

        is.boxed().sorted((a, b) -> Math.random() > .5 ? 1 : -1).forEach(System.out::println);

        Stream<Integer> ss = Stream.of(1, 5, 2, 35, 15, 9);
        ss.sorted((a, b) -> Math.random() > .5 ? -1 : 1).forEach(System.out::println);

        //LongStream
        //DoubleStream
        //IntStream  相同  Stream<Integer>
        //Stream<String>
    }

    public static void hello(String[] args) {
        //生成一IntStream，数据为随机整数1-100
        var rand = new Random();
        //rand.nextInt(1,5) 生成1-4的随机整数，没有5
        var is = IntStream.generate(() -> rand.nextInt(1, 101)).limit(50);

        //DoubleStream.generate() 生成5个随机小数
        var ns = DoubleStream.generate(Math::random).limit(15);
        ns.forEach(System.out::println);

        //System.out.println(ns.count()); 错误的，流是一次操作

        //IntStream.iterate(2, a -> a + 2).limit(15).forEach(System.out::println);
        IntConsumer ic = System.out::println;
        var is2 = IntStream.iterate(10, e -> e + 10).limit(5);
        Stream<Integer> si = is2.boxed();
        Integer[] iii = new Integer[5];
        si.collect(Collectors.toList()).toArray(iii);
        System.out.println(Arrays.toString(iii));


    }

    public static void demo(String[] args) {
        IntStream is = IntStream.empty();
        var is2 = IntStream.of(1, 2, 3);
        System.out.println(is2.count());
        var is3 = IntStream.of(10);
        System.out.println(is3.count());
        var is4 = IntStream.rangeClosed(1, 100);
        System.out.println(is4.count());
        var is5 = IntStream.range(1, 10);
        System.out.println(is5.count());
        var is6 = IntStream.iterate(1, e -> e + 2).limit(6);
        //System.out.println(is6.count());
        is6.forEach(System.out::println);


        //面试题2018 计算1+2+3+...+100 = sum (不允许使用循环递归,不能直接写结果)
        var issum = IntStream.rangeClosed(1, 100);
        System.out.println("1+2+3+...+100 = " + issum.sum());

    }
}
